import axios from 'axios'
import React, { Component } from 'react'

export default class TodoHeader extends Component {
  state = {
    name: '',
  }
  render() {
    const { name } = this.state
    return (
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          placeholder="What needs to be done?"
          autoFocus
          value={name}
          onChange={(e) => this.setState({ name: e.target.value.trim() })}
          onKeyUp={this.add}
        />
      </header>
    )
  }
  // add
  add = async (e) => {
    // console.log(e.code)
    if (e.code === 'Enter') {
      // 如果没有数据 直接返回
      if (!this.state.name) return
      //发送请求添加数据
      await axios.post('http://localhost:8888/todos', {
        name: this.state.name,
        done: false,
      })
      // 重新渲染
      this.props.getTodoList()
      //清除输入框内容
      this.setState({
        name: '',
      })
    }
  }
}
